package com.orangelife.mobile.surrounding.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.curry.android.adapter.FatherAdapter;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.view.stickylistheaders.ExpandableStickyListHeadersListView;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.PullRefreshBaseActivity;
import com.orangelife.mobile.common.view.EmptyLayout;
import com.orangelife.mobile.main.adapter.HotGoodsListViewAdapter;
import com.orangelife.mobile.shoppingcart.activity.ShoppingCartActivity;
import com.orangelife.mobile.shoppingcart.biz.ShoppingCartBiz;
import com.orangelife.mobile.surrounding.adapter.GoodListLeftAdapter;
import com.orangelife.mobile.surrounding.adapter.GoodListRightAdapter;
import com.orangelife.mobile.surrounding.biz.SurroundHttpBiz;
import com.orangelife.mobile.util.BLog;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 周边商户的商品列表
 * Created on 2016/1/21.
 *
 * @author 绯若虚无
 * @version v3.4
 */
public class SurroundingGoodListActivity extends PullRefreshBaseActivity implements  AdapterView.OnItemClickListener{
    @Bind(R.id.llSearch)
    LinearLayout llSearch;
    @Bind(R.id.flShoppingCart)
    FrameLayout ibShoppcar;
    /** 购物车的数量 */
    @Bind(R.id.tvGoodNumber)
    TextView tvGoodNumber;

    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.emptyLayout)
    EmptyLayout emptyLayout;
    @Bind(R.id.tvTitle)
    TextView tvTitle;

    @Bind(R.id.leftView)
    ListView leftView;
    @Bind(R.id.rightList)
    ExpandableStickyListHeadersListView rightView;

    private HotGoodsListViewAdapter<List<Map<String, Object>>> adapter;
    private GoodListLeftAdapter<List<Map<String, Object>>> leftAdapter;
    private GoodListRightAdapter<List<Map<String, Object>>> rightAdapter;
    private List<List<Map<String, Object>>> refreshList = new ArrayList<>();
    ;
    private String merID = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_surrounding_good_list);
        ButterKnife.bind(this);
        setListViewAdapter();
        getIntentInfo();
        showProgress();
    }


    private void getIntentInfo() {
        String title = getIntent().getStringExtra("merchantName");
        setTitle(title);
    }


    private void setTitle(String title) {
        if (StringUtil.isBlank(title)) {
            title = "热门商品";
        }
        tvTitle.setText(title);
    }
    List listLeft = null;
    List listRight = null;
    private final int WHAT_LIST = 1;
    public static final int WHAT_NO_NET = -2;
    Handler handler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case WHAT_NO_NET:
                    dismissEmptyLayout();
                case WHAT_LIST:
                    listLeft = SurroundHttpBiz.getGoodListLeft(msg.obj);
                    listRight = SurroundHttpBiz.getGoodListRight(msg.obj);
                    updateListView(listLeft,leftAdapter);
                    updateListView(listRight,rightAdapter);
                    dismissEmptyLayout();
                    leftAdapter.setColorItem(0);
                    break;
                case 500:
                    dismissEmptyLayout();
                    ToastHelper.getInstance()._toast(
                            "网络不稳定");
                    break;
                case 1011:
                    dismissEmptyLayout();
                    isLogin(dialog);
                    break;
                default:

                    break;
            }
        }
    };

    @OnClick({R.id.llSearch, R.id.flShoppingCart, R.id.ivBack})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llSearch:
                //跳转搜索界面
                IntentHelper.getInstances().getIntent(SurroundingGoodListActivity.this, SearchConditionActivity.class);
                break;
            case R.id.flShoppingCart:
                IntentHelper.getInstances().getIntent(SurroundingGoodListActivity.this, ShoppingCartActivity.class);
                break;
            case R.id.ivBack:
                finish();
                break;
        }
    }

    private void dismissEmptyLayout() {
        if (getEmptyLayout() != null) {
            getEmptyLayout().dismiss();
        }
    }
    private void updateListView(List list, FatherAdapter adapter) {
        List refreshList = new ArrayList();

        if (list != null && list.size() > 0) {
            refreshList.addAll(list);
        }
        if (adapter != null) {
            adapter.setList(refreshList);
            adapter.notifyDataSetChanged();
        }
    }
    private int winItemCount=0;
    private boolean touch=false;
    private int lfetVisibleItemCount=0;
    private void setListViewAdapter() {


        leftAdapter = new GoodListLeftAdapter<>(this, refreshList);
        rightAdapter= new GoodListRightAdapter<>(this, refreshList);
        leftView.setAdapter(leftAdapter);
        rightView.setAdapter(rightAdapter);

        leftView.setOnItemClickListener(this);
        rightView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                touch = true;
                return false;
            }
        });

        leftView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                lfetVisibleItemCount=visibleItemCount;
            }
        });
        rightView.setOnScrollListener(new AbsListView.OnScrollListener() {
            private  int item=0;
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }
            /**
             * 正在滚动
             * firstVisibleItem第一个Item的位置
             * visibleItemCount 可见的Item的数量
             * totalItemCount item的总数
             */
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                winItemCount=0+visibleItemCount;
                if(listLeft!=null&&touch)
                    for (int i=0;i<listLeft.size();i++){
                        Map<String,String> map=(Map<String,String> )listLeft.get(i);
                        int position=Integer.parseInt(map.get("count") + "");
                        if(position==firstVisibleItem){
                            if(position>lfetVisibleItemCount||position==0)
                                leftView.setSelection(i);


                            leftAdapter.setColorItem(i);
                           // item=firstVisibleItem;
                            return;
                        }
                    }
            }
        });
    }

    /** 设置购物车商品数量 */
    private void setShoppingCarNumber() {
        int goodNum = ShoppingCartBiz.getGoodsCount();
        if (goodNum == 0) {
            tvGoodNumber.setVisibility(View.GONE);
        } else {
            tvGoodNumber.setVisibility(View.VISIBLE);
            tvGoodNumber.setText(goodNum + "");
        }
    }

    @Override
    protected EmptyLayout getEmptyLayout() {
        return emptyLayout;
    }

    @Override
    protected List getData() {
        return refreshList;
    }

    @Override
    protected int getDataCount() {
        int count = 0;
        int lastElement;
        if (refreshList.size() > 0) {
            lastElement = refreshList.get(refreshList.size() - 1).size();
            count = (refreshList.size() - 1) * 2 + lastElement;
        }
        return count;
    }

    @Override
    protected void requestWhenPullRefresh() {
        if ("".equals(merID)) {
            merID = getIntent().getStringExtra("merID");
        }
  //    SurroundHttpBiz.getGoodList(isConnected(false), pageNo, pageSize, merID, handler, WHAT_LIST);
        SurroundHttpBiz.requestGoodsList(merID, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                if(errCode==1011){
                    dismissEmptyLayout();
                    isLogin(dialog);
                }else if (errCode == 00) {
                    String str = response.toString();
                    listLeft = SurroundHttpBiz.getGoodListLeft(str);
                    listRight = SurroundHttpBiz.getGoodListRight(str);
                    updateListView(listLeft, leftAdapter);
                    updateListView(listRight, rightAdapter);
                    dismissEmptyLayout();
                    leftAdapter.setColorItem(0);
                }else{
                    dismissEmptyLayout();
                    ToastHelper.getInstance()._toast(
                            "网络不稳定");
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        setShoppingCarNumber();
        BLog.getInstance().intAppmod(BLog.NEARBY);
    }

    @Override
    public void onStop() {
        super.onStop();
        BLog.getInstance().outAppmod(BLog.NEARBY);
    }

    Map<String,Object> listOnItem= new HashMap<String,Object>();
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.leftView:
                onItemClickLeft(view,position);

                break;

            default:
                break;
        }
    }

    /**
     * 点击左边选着右边
     * @param view
     * @param position
     */

    private void onItemClickLeft(View view,int position){

        touch=false;
        Map<String, String> map = (Map<String, String>) listLeft.get(position);
        int i=Integer.parseInt(map.get("count")+"");
        if(listRight.size()>winItemCount)
         rightView.setSelection(i);
        leftAdapter.setColorItem(position);
        setLeftItemState(view, position);

    }

    /**
     * 保存左边按钮状态
     * @param view
     * @param position
     */
    private void setLeftItemState(View view,int position){
        LinearLayout ll=(LinearLayout)view;
        if(ll== null){
            return;
        }

        TextView tv= (TextView)ll.getChildAt(0);
        ll.setBackgroundResource(R.color.white);
        leftAdapter.setReplaceColorItem(position);
        tv.setTextColor(Color.parseColor("#fff57c24"));
        if(listOnItem.size()==0){
            listOnItem.put("position", position);
            listOnItem.put("obj",ll);
            listOnItem.put("tv", tv);
            if(position!=0)
                leftAdapter.setHeaderView();
        }else{
            if(Integer.parseInt(listOnItem.get("position")+"")!=position){
                LinearLayout obj=(LinearLayout)listOnItem.get("obj");
                TextView oldtv= (TextView)listOnItem.get("tv");
                obj.setBackgroundResource(R.color.InputGray);
                oldtv.setTextColor(Color.parseColor("#535353"));
                listOnItem.remove("position");
                listOnItem.remove("obj");
                listOnItem.remove("tv");
                listOnItem.put("position", position);
                listOnItem.put("obj",ll);
                listOnItem.put("tv",tv);
            }
        }
    }

}
